package dir_tree

import (
	"file_explorer/common/log"
	"sort"

	"file_explorer/common/util"
	"file_explorer/model"
	"file_explorer/service"
	"file_explorer/view/packed_widgets"
	"file_explorer/view/store"
)

func SetDirTreeEvents(gCtx *store.GlobalContext, tree *packed_widgets.Tree) {
	tree.OnBranchOpen = func(node *packed_widgets.TreeNode) {
		log.Info("展开目录：%s", node.NodeId)
		// 查询子目录
		subDirs, err := service.QueryFiles(node.NodeId,
			model.GetDefaultOption().
				SetFilter(func(info *model.FileInfo) bool {
					return info.IsDir()
				}),
		)

		if err != nil {
			return
		}

		sort.Slice(subDirs, func(i, j int) bool {
			return util.CmpText(subDirs[i].Name, subDirs[j].Name) > 0
		})

		// 构造子节点
		tree.Data[node.NodeId].Children = make([]*packed_widgets.TreeNode, len(subDirs))
		for index, subDir := range subDirs {
			childNodeId := util.PathJoin(node.NodeId, subDir.Name)
			tree.Data[childNodeId] = &packed_widgets.TreeNode{
				NodeId: childNodeId,
				Label:  subDir.Name,
				Depth:  node.Depth + 1,
				Parent: node,
			}
			tree.Data[node.NodeId].Children[index] = tree.Data[childNodeId]
		}
	}

	tree.OnDoubleTapped = func(node *packed_widgets.TreeNode) {
		log.Info("打开目录：%s", node.NodeId)
		fileTabContext := store.NewFileTabContext(gCtx, node.NodeId)
		gCtx.AddTab(fileTabContext)
	}
}

func NewDirTree(gCtx *store.GlobalContext) *packed_widgets.Tree {
	rootNode := &packed_widgets.TreeNode{
		NodeId: "/", // 绝对路径
		Label:  "/", // 显示名称
		Depth:  0,
	}

	tree := packed_widgets.NewTree(&packed_widgets.TreeNode{
		NodeId:   "",
		Label:    "\\",
		Children: []*packed_widgets.TreeNode{rootNode},
	})

	SetDirTreeEvents(gCtx, tree)

	return tree
}
